<?php
/**
 * Save.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/05/11
 * Time: 12:06
 */
namespace app\api\open\commodity;

use app\api\model\BrandModel;
use app\api\model\GoodsCategoryJoinModel;
use app\api\model\GoodsModel;
use app\api\model\GoodsRegionJoinModel;
use app\api\model\GoodsSpecModel;
use app\api\open\Base;
use think\Db;
use think\Validate;

class Save extends Base
{
    protected $goods_id = null;
    protected $goodsData = [];
//    protected $goodsCategoryJoinData = [];
//    protected $goodsRegionJoinData = [];
    protected $goodsSpecData = [];

    /**
     * Save constructor.
     * @throws \Exception
     */
    public function __construct($param=[])
    {
        parent::__construct($param);

        $param = $this->params;

        // 验证请求参数
        $validate = new Validate([
            // step1
            "brand_id" => "require",
            "brand_name" => "require",
            "title" => "require",
            "title_color" => "require",
            "model" => "require",
            "region_type" => "require",
            "inventory" => "require",
            "inventory_unit" => "require",
            "images" => "require",
            "original_price" => "require",
            "min_original_price" => "require",
            "max_original_price" => "require",
            "price" => "require",
            "min_price" => "require",
            "max_price" => "require",
            "give_integral" => "require",
            "buy_min_number" => "require",
            "buy_max_number" => "require",
            "is_deduction_inventory" => "require",
            "is_shelves" => "require",
            "is_home_recommended" => "require",
            "photo_count" => "require",
            "sales_count" => "require",
            "access_count" => "require",
            "attr_list" => "require",

            "category1" => "require",
            "category2" => "require",
            "category3" => "require",
            "category1_name" => "require",
            "category2_name" => "require",
            "category3_name" => "require",

            "region_list" => "require",

            "photo_list" => "require",
            // step2
            "rows" => "require",
            "cols" => "require",
            // step3
            "content_web" => "require",
        ]);
        $check = $validate->check($param);
        if($check === false){
            // 验证失败 输出错误信息
            throw new \Exception($validate->getError(),1);
        }
        if(!empty($param['id']))
        {
            $this->goods_id = $param['id'];
        }

        // 品牌ID
        $brand_id = intval($param['brand_id']);
//        $brandInfo = BrandModel::getInstance()->getInfoById($brand_id,'is_enable');
//        if(empty($brandInfo['is_enable']))
//        {
//            throw new \Exception("查询品牌为空",1);
//        }
        // 商店ID
        if(isset($param['store_id']))
        {
            $this->goodsData['store_id'] = (int)$param['store_id'];
        }
        // 供应商ID
        if(isset($param['supplier_id']))
        {
            $this->goodsData['supplier_id'] = (int)$param['supplier_id'];
        }
        // 品牌ID
        $this->goodsData['brand_id'] = $brand_id;
        // 品牌名称
        $this->goodsData['brand_name'] = (string)$param['brand_name'];
        // 标题
        $this->goodsData['title'] = (string)$param['title'];
        // 标题颜色
        $this->goodsData['title_color'] = (string)$param['title_color'];
        // 型号
        $this->goodsData['model'] = (string)$param['model'];
        // 地区配送（0支持,1不支持）
        $this->goodsData['region_type'] = $param['region_type']==1?1:0;
        // 库存（所有规格库存总和）
        $this->goodsData['inventory'] = intval($param['inventory']);
        // 库存单位
        $this->goodsData['inventory_unit'] = (string)$param['inventory_unit'];
        // 封面图片
        $this->goodsData['images'] = (string)$param['images'];
        // 原价（单值:10, 区间:10.00-20.00）一般用于展示使用
        $this->goodsData['original_price'] = (string)$param['original_price'];
        // 最低原价
        $this->goodsData['min_original_price'] = round($param['min_original_price'],2);
        // 最大原价
        $this->goodsData['max_original_price'] = round($param['max_original_price'],2);
        // 销售价格（单值:10, 区间:10.00-20.00）一般用于展示使用
        $this->goodsData['price'] = (string)$param['price'];
        // 最低价格
        $this->goodsData['min_price'] = round($param['min_price'],2);
        // 最高价格
        $this->goodsData['max_price'] = round($param['max_price'],2);
        // 购买赠送积分
        $this->goodsData['give_integral'] = intval($param['give_integral']);
        // 最低起购数量 （默认1）
        $this->goodsData['buy_min_number'] = intval($param['buy_min_number']);
        // 最大购买数量（最大数值 100000000, 小于等于0或空则不限）
        $this->goodsData['buy_max_number'] = intval($param['buy_max_number']);
        // 是否扣减库存（0否, 1是）
        $this->goodsData['is_deduction_inventory'] = $param['is_deduction_inventory']==1?1:0;
        // 是否上架（下架后用户不可见, 0否, 1是）
        $this->goodsData['is_shelves'] = $param['is_shelves']==1?1:0;
        // 是否首页推荐（0否, 1是）
        $this->goodsData['is_home_recommended'] = $param['is_home_recommended']==1?1:0;
        // 电脑端详情内容
        $this->goodsData['content_web'] = (string)$param['content_web'];
        // 相册图片数量
        $this->goodsData['photo_count'] = intval($param['photo_count']);
        // 销量
        $this->goodsData['sales_count'] = intval($param['sales_count']);
        // 访问次数
        $this->goodsData['access_count'] = intval($param['access_count']);
        // 短视频
        $this->goodsData['video'] = empty($param['video'])?"":$param['video'];
        // 首页推荐图片
        $this->goodsData['home_recommended_images'] = empty($param['home_recommended_images'])?"":$param['home_recommended_images'];
        // 是否已删除（0 未删除, 大于0则是删除时间）
        $this->goodsData['is_delete_time'] = empty($param['is_delete_time'])?0:time();

        // 规格列
        $cols = json_decode($param['cols'],true);
        if(!empty($cols) && is_array($cols))
        {
            $spec_cols = [];
            foreach ($cols as $col)
            {
                $spec_cols[] = $col['value'];
            }
            $this->goodsData['spec_cols'] = json_encode($spec_cols);
        }

        // 自定义属性
        $attr_list = json_decode($param['attr_list'],true);
        if(!empty($attr_list) && is_array($attr_list))
        {
            $this->goodsData['attr_list'] = json_encode($attr_list);
        }else{
            $this->goodsData['attr_list'] = '[]';
        }

        // 商品相册图片关联数据
        $photo_list = json_decode($param['photo_list'],true);
        if(!empty($photo_list) && is_array($photo_list))
        {
            $this->goodsData['photo_list'] = json_encode($photo_list);
        }else{
            $this->goodsData['photo_list'] = '[]';
        }

        // 商品分类关联数据
        $this->goodsData['category_tree'] = ",{$param['category1']},{$param['category2']},{$param['category3']},";
        $this->goodsData['category_name_tree'] = "_{$param['category1_name']}_{$param['category2_name']}_{$param['category3_name']}_";
//        $this->goodsCategoryJoinData[] = $param['category1'];
//        $this->goodsCategoryJoinData[] = $param['category2'];
//        $this->goodsCategoryJoinData[] = $param['category3'];

        // 商品配送地区关联数据
        $region_list = json_decode($param['region_list'],true);
        if(!empty($region_list) && is_array($region_list))
        {
            $this->goodsData['region_list'] = json_encode($region_list);
        }else{
            $this->goodsData['region_list'] = '[]';
        }

        /**
         * 商品规格关联数据
         */
        $rows = json_decode($param['rows'],true);
        foreach ($rows as &$row)
        {
            $temp = [];
            // 规格中 value
            $temp['value'] = json_encode($row['cols']);
            // 销售价格
            $temp['price'] = round($row['price'],2);
            if($temp['price'] < 0)
            {
                throw new \Exception("销售价格不能为负数",1);
            }
            // 库存
            $temp['inventory'] = intval($row['inventory']);
            if($temp['inventory'] < 0)
            {
                throw new \Exception("库存不能为负数",1);
            }
            // 重量（kg）
            $temp['weight'] = round($row['weight'],2);
            if($temp['weight'] < 0)
            {
                throw new \Exception("重量不能为负数",1);
            }
            // 编码
            $temp['coding'] = (string)$row['coding'];
            // 条形码
            $temp['barcode'] = (string)$row['barcode'];
            // 图片
            $temp['images'] = (string)$row['images'];
            // 上下架
            $temp['is_shelves'] = empty($row['is_shelves'])?0:1;
            // 原价
            $temp['original_price'] = round($row['original_price'],2);
            if($temp['original_price'] < 0)
            {
                throw new \Exception("原价不能为负数",1);
            }
            // id
            $temp['id'] = empty($row['id'])?"":$row['id'];

            // 规格参数
            $this->goodsSpecData[] = $temp;
        }
    }

    public function index($param=[])
    {
        Db::startTrans();
        try
        {
            // 保存商品主表信息
            $status = GoodsModel::getInstance()->save($this->goods_id,$this->goodsData);
            if(!$status)
            {
                throw new \Exception("【保存1】保存商品信息失败",2);
            }

            // 获取 goods_id
            $goods_id = $this->goods_id===null?$status:$this->goods_id;

//            if($this->goods_id!==null)
//            {
//                // 编辑情况下删除该商品关联的所有分类
//                $status = GoodsCategoryJoinModel::getInstance()->delByGoodsId($goods_id);
//                if(!$status)
//                {
//                    throw new \Exception("【保存2】删除商品关联分类信息失败",2);
//                }
//            }
//
//            // 批量添加商品的分类
//            $status = GoodsCategoryJoinModel::getInstance()->batch($goods_id,$this->goodsCategoryJoinData);
//            if(!$status)
//            {
//                throw new \Exception("【保存3】批量添加商品的分类失败",2);
//            }

//            if($this->goods_id!==null) {
//                // 编辑情况删除该商品关联的所有地区
//                $status = GoodsRegionJoinModel::getInstance()->delByGoodsId($goods_id);
//                if (!$status) {
//                    throw new \Exception("【保存4】删除商品关联地区信息失败", 2);
//                }
//            }
//
//            if(!empty($this->goodsRegionJoinData))
//            {
//                // 批量添加商品的地区
//                $status = GoodsRegionJoinModel::getInstance()->batch($goods_id,$this->goodsRegionJoinData);
//                if(!$status)
//                {
//                    throw new \Exception("【保存5】批量添加商品的地区失败",2);
//                }
//            }

            // 批量保存商品规格
            GoodsSpecModel::getInstance()->batchSave($goods_id,$this->goodsSpecData);
        }
        catch (\Exception $e)
        {
            // 出现错误进行回滚处理
            Db::rollback();
            // 统一错误抛出
            throw new \Exception("保存失败：".$e->getMessage(),$e->getCode());
        }

        Db::commit();
        return ['goods_id'=>$goods_id];
    }
}